import React, { ReactPropTypes, useContext, useEffect, useState } from "react";
import blogservice from "../../../services/blogservice";
import { Button, ButtonGroup, Card, Col, Container, FormCheck, ListGroup, ListGroupItem, Row } from "react-bootstrap";
import * as Icons from 'react-bootstrap-icons';
import "./index.css";
import moment from "moment";
import { PopupDialog } from "../../../components/common";
import { useNavigate } from "react-router-dom";
import ArticleList,{ArticleItem} from "../../../components/layout/ArticleList";
import { AuthenticationContext } from "../../../context";

const Articles = (props:{},state:{})=>{

    const [articles,setArticles] = useState<Array<any>>([]);
    const [isEdit,setIsEdit] = useState(false);
    const [selectedCount,setSelectedCount] = useState(0);
    const navigate = useNavigate();
    const {userInfo} = useContext(AuthenticationContext);

    useEffect(()=>{
        refreshData();
    },[])

    const refreshData = ()=> {
        blogservice.loadArticles(userInfo.userid).then((resp:any)=>{
            let articles = (resp.content.records||[]).map((item:any,index:number)=>{
                return {
                    ...item,
                    createtime:moment.unix(item.createtime).format("yyyy-MM-DD HH:mm:SS"),
                    isDraft:item.status === 0,
                    isSelected:false,
                }
            })
            setArticles(articles);
        }).catch((err)=>{
            PopupDialog.showBsError(err);
        })
    }

    const onPressEditButton = (e:any)=> {
        // e.target.preventDefaults();
        var selectedArticles:Array<any> = findSelectedItems(articles);
        if(isEdit && selectedCount > 0){
            //TODO: calll api to delete the selected articles;
            PopupDialog.showBSPopup({message:"Do you want to delete these articles?"},()=>{
                const ids = selectedArticles.map((item)=>{
                    return item.articleid
                })
                blogservice.removeArticles(userInfo.userid,ids).then(()=>{
                    PopupDialog.showBSPopup({message:"delete articles successfully"},()=>{
                        refreshData();
                    });
                }).catch((err)=>{
                    PopupDialog.showBsError(err);
                })
            })
        }else{
            selectedArticles.forEach((item:any)=>{
                item.isSelected = false;
            })
        }
        setSelectedCount(0);
        setIsEdit(!isEdit);
    }

    const onPressItemAtIndex = (index:number)=> {
        var atks = Array.from(articles);
        var article:any = atks.at(index);
        article.isSelected = !article.isSelected;
        const selectedItems = findSelectedItems(atks);
        setSelectedCount(selectedItems.length);
        setArticles(atks);
    }

    const findSelectedItems = (items:Array<any>)=> {
        return items && items.filter((item:any,index)=>{
            return item.isSelected === true;
        })
    }

    const onPressItem = (idx:number,item?:ArticleItem)=>{
        if(isEdit){
           onPressItemAtIndex(idx);
       }else{
           navigate("/blog/editor",{state:{
               article:item
           }})
           // window.location.assign(item.url)
       }
   }

   const onPressItemLink = (url:string)=>{
     window.open(url)
   }

    return <Container className="d-flex flex-column listContainer" fluid>
    {/* add flush to make the list group with sharp corner*/}
    <Container className="d-flex flex-row justify-content-end me-0 pe-0 pt-1" fluid>
       { articles && articles.length > 0 ?(isEdit ? (selectedCount === 0 ? <Button variant="light" className="text-dark" size="sm" onClick={onPressEditButton}>Cancel</Button> : <Button variant="outline-danger" size="sm" onClick={onPressEditButton}>Delete({selectedCount})</Button>)  : <Button variant="outline-info" size="sm" onClick={onPressEditButton}>Edit</Button>) :null}
    </Container>
    <ArticleList articles={articles} isEdit={isEdit} onPressItem={onPressItem} onPressLink={onPressItemLink}/>
    </Container>
}

export default Articles;